import { useImportImg } from "@/hooks"
const warningIcon = useImportImg("warning-icon")

/**
 * 对象值比较，并返回新旧值
 * @param {Object} oldValue 旧值
 * @param {Object} newValue 新值
 * @returns {Object} 有变化的值
 */
const useObjectDiff = (oldValue, newValue) => {
  if(!Object.keys(oldValue).length) return {}
  const diff = {}
  for (let key in newValue) {
    if (newValue[key] !== oldValue[key]) {
      diff[key] = {
        oldValue: oldValue[key],
        newValue: newValue[key],
      }
    }
  }
  return diff
}
const diffKey = {
  'retailPrice': '零售价',
  'wholesalePrice': '批发价',
  'salesStatus': '销售状态',
  'wholesaleStatus': '批发状态'
}

/**
 * 值比较，调用该方法时，会弹出对话框提示用户是否保存
 * @param {Object} oldValue 旧值
 * @param {Object} newValue 新值
 * @returns {Promise<Boolean>} true : 确认保存或无变化 false : 取消保存
 */
export default function useDiffValue(oldValue, newValue) {
  return new Promise((resolve, reject) => {
    const diffObj = useObjectDiff(oldValue, newValue);
    const diffList = Object.keys(diffObj).map(item => {
      if(item === 'salesStatus' || item === 'wholesaleStatus'){
        const oldText = diffObj[item].oldValue === 1 ? '正常' : item === 'salesStatus' ? '停售' : '停发'
        const newText = diffObj[item].newValue === 1 ? '正常' : item === 'salesStatus' ? '停售' : '停发'
        return `<div class="diffItem"><span class="diffItem-label">${diffKey[item]}：</span>由${oldText}修改为${newText}</div>`
      }
      return `<div class="diffItem"><span class="diffItem-label">${diffKey[item]}：</span>由${diffObj[item].oldValue}修改为${diffObj[item].newValue}</div>`
    })
    const title = `<div style="display:flex;align-items:center;color:#222;font-size:14px;padding:0 14px;">
      <img src="${warningIcon}" style="width:40px;height:40px;margin-right:10px"></img>
      <span>系统检测到以下字段值发生变化。是否确认修改？</span>
    </div>`
    if(diffList.length){
      ElMessageBox.confirm(`${title}<div style="padding-left:64px">${diffList.join('')}</div>`,'提示',{
        dangerouslyUseHTMLString: true,
        roundButton: true,
      }).then(()=>{
        resolve(true)
      }).catch(()=>{
        resolve(false)
      })
    }else{
      resolve(true)
    }
  })
}